<?php
/**
 * @author Elwin
 * @version 20121226
 */
class PositionController extends Controller {
	public function init() {
		$d = Yii::app ()->db->createCommand ( 'select * from ' . Position::model ()->tableName () )->queryRow ();
		// print_r($d);
		// print_r ( Yii::app ()->db->autoConnect );
	}
	public function actionView($id) {
		$this->render ( 'view', array (
				'model' => $this->loadModel ( $id ) 
		) );
	}
	/**
	 * 添加职位
	 */
	public function actionCreate() {
		$position = new Position ();
		$position->unsetAttributes ();
		$post = $this->getPost ( 'Position' );
		$newname = $this->getPost ( 'newname' );
		$parentid = $post ['id'];
		$data = $position->findByPk ( $parentid );
		$attributes = array (
				'parentid' => $parentid,
				'name' => $newname,
				'dutyid' => $data->dutyid,
				'description' => $newname,
				'state' => 1,
				'order' => $data->order + 1,
				'cid' => $data->cid,
				'deptid' => $data->deptid,
				'createtime' => $_SERVER ['REQUEST_TIME'],
				'updatetime' => $_SERVER ['REQUEST_TIME'] 
		);
		$position->setAttributes ( $attributes, false );
		$position->setScenario ( 'insert' );
		$position->setIsNewRecord ( true );
		if ($position->save ()) {
			$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
			$cacheKey = $cacheName [0];
			Yii::app ()->cache->delete ( $cacheKey );
			$this->ajaxReturn ( $position->attributes, '添加节点成功!', 1 );
		} else {
			$this->ajaxReturn ( '', '添加节点失败!', 0 );
		}
	}
	
	/**
	 * 更新职位
	 */
	public function actionUpdate() {
		$id = $this->getPost ( 'id' );
		$model = $this->loadModel ( $id );
		if (isset ( $_POST ['Position'] )) {
			$model->attributes = $this->getPost ( 'Position' );
			if ($model->save ()) {
				$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
				$cacheKey = $cacheName [0];
				Yii::app ()->cache->delete ( $cacheKey );
				
				$this->ajaxReturn ( $model->attributes, '更新成功!', 1 );
			} else {
				$this->ajaxReturn ( '', '更新失败!', 0 );
			}
		}
	}
	/**
	 * 刪除职位
	 */
	public function actionDelete() {
		$id = $this->getPost ( 'id' );
		if (! empty ( $id )) {
			if (Position::model ()->updateByPk ( $id, array (
					'state' => 2 
			) )) {
				$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
				$cacheKey = $cacheName [0];
				Yii::app ()->cache->delete ( $cacheKey );
				$this->ajaxReturn ( '', '删除成功!', 1 );
			} else {
				$this->ajaxReturn ( '', '删除失败!', 0 );
			}
		}
	}
	/**
	 * 所有职位
	 */
	public function actionIndex() {
		if (false === ($jsonTree = Yii::app ()->dbcache->get ( 'dataTree' ))) {
			$sql = 'SELECT a.id,a.cid,a.parentid,CONCAT_WS(" ", a.name, CONCAT_WS("","(",b.name,")")) AS name FROM ' . Position::model ()->tableName () . ' a LEFT JOIN ' . Depth::model ()->tableName () . ' b ON(a.deptid=b.id) WHERE a.state=1 ORDER BY a.parentid,a.order ASC';
			$data = Yii::app ()->db->createCommand ( $sql )->queryAll ();
			$position = new Position ();
			$dataTree = $position->buildTree ( $data );
			$jsonTree = json_encode ( $dataTree );
			Yii::app ()->dbcache->set ( 'dataTree', $jsonTree, 10 );
			echo '查询存储';
		}
		// print_r($jsonTree);
		$this->render ( 'index', array (
				'jsonTree' => $jsonTree 
		) );
	}
	/**
	 * 在tree中实现拖拽
	 */
	public function actionDrag() {
		$source = $this->getPost ( 'a' );
		$tagert = $this->getPost ( 'b' );
		$dragType = $this->getPost ( 'dragtype' );
		if (in_array ( $dragType, array (
				'prev',
				'next' 
		) ) && $source ['parentid'] == $tagert ['parentid']) {
			$method = 'horizontalDrag';
		} else {
			$method = 'innerDrag';
		}
		call_user_func_array ( array (
				$this,
				$method 
		), array (
				$source,
				$tagert,
				$dragType 
		) );
	}
	/**
	 * 实现树节点中的水平拖拽
	 *
	 * @param array $source
	 *        	拖动节点
	 * @param array $tagert
	 *        	目标节点
	 * @param string $dragType
	 *        	拖动节点相对目标节点位置(prev or next)
	 */
	protected function horizontalDrag($source, $tagert, $dragType) {
		$position = new Position ();
		$sourcePid = $source ['parentid'];
		$tagertPid = $tagert ['parentid'];
		if ($sourcePid == $tagertPid) {
			// 在当前节点下移动,父节点没有改变
			$sql = 'SELECT id,cid,parentid,deptid,dutyid,name FROM ' . Position::tableName () . ' WHERE parentid = :parentid ORDER BY `order` ASC';
			$command = Yii::app ()->db->createCommand ( $sql );
			$command->bindParam ( ':parentid', $tagertPid );
			$rows = $command->queryAll ();
			foreach ( $rows as $k => $row ) {
				if ($row ['id'] == $source ['id'])
					$sourceIndex = $k;
				if ($row ['id'] == $tagert ['id'])
					$targetIndex = $k;
			}
			if ($sourceIndex > $targetIndex && $dragType == 'next')
				$targetIndex += 1;
			$rows = WArray::moveToByIndex ( $rows, $sourceIndex, $targetIndex );
			$this->resetChildrenOrder ( $rows );
		} else {
			// 移动到其它节点下,改变了当前节点的父节点
			// $source ['parentid'] = $newPid = $tagert ['parentid'];
		}
	}
	/**
	 * 实现不同父节点的拖拽
	 *
	 * @param array $source
	 *        	拖动节点
	 * @param array $tagert
	 *        	目标节点
	 * @param string $dragType
	 *        	拖动节点相对目标节点位置(prev or next)
	 */
	protected function innerDrag($source, $tagert, $dragType) {
		$source ['parentid'] = $tagert ['parentid'];
		$position = new Position ();
		if ($dragType == 'next' || $dragType == 'prev') {
			$parentid = $tagert ['parentid'];
		} elseif ($dragType == 'inner') {
			// 目标节点为父节点, target.id为拖拽节点的父节点
			$parentid = $tagert ['id'];
		}
		// 更新拖动节点的父节点id
		$source ['parentid'] = empty ( $parentid ) ? 0 : $parentid;
		$sql = 'SELECT id,cid,parentid,deptid,dutyid,name FROM ' . Position::tableName () . ' WHERE parentid=:parentid';
		$command = Yii::app ()->db->createCommand ( $sql );
		$command->bindParam ( ':parentid', $parentid );
		$rows = $command->queryAll ();
		$tagertIndex = 0;
		foreach ( $rows as $k => $row ) {
			if ($tagert ['id'] == $row ['id']) {
				$tagertIndex = $k;
			}
		}
		if ($dragType == 'next') {
			$tagertIndex += 1;
		} elseif ($dragType == 'inner') {
			$tagertIndex = count ( $rows ) + 1;
		}
		$rows = $this->arrayInsert ( $rows, $tagertIndex, $source );
		$this->resetChildrenOrder ( $rows );
		
		$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
		$cacheKey = $cacheName [0];
		Yii::app ()->cache->delete ( $cacheKey );
	}
	/**
	 * 在数组中某个位置插入值
	 *
	 * @param array $array
	 *        	数组
	 * @param int $pos
	 *        	插入位置
	 * @param string $val
	 *        	插入的值
	 * @return array $array 返回结果
	 */
	function arrayInsert($array, $pos, $val) {
		$array2 = array_splice ( $array, $pos );
		$array [] = $val;
		$array = array_merge ( $array, $array2 );
		return $array;
	}
	public function actionAdmin() {
		$model = new Position ( 'search' );
		$model->unsetAttributes ();
		if (isset ( $_GET ['Position'] ))
			$model->attributes = $_GET ['Position'];
		
		$this->render ( 'admin', array (
				'model' => $model 
		) );
	}
	public function loadModel($id) {
		$model = Position::model ()->findByPk ( $id );
		if ($model === null)
			throw new CHttpException ( 404, 'The requested page does not exist.' );
		return $model;
	}
	
	/**
	 * 输出对应部门id的职位列表option
	 */
	public function actionPositionlist($deptid) {
		$deptid = intval ( $deptid );
		$arr = Position::getDeptidPosition ( $deptid );
		$str = "";
		foreach ( $arr as $k => $v ) {
			$str .= '<option value="' . $k . '">' . $v . '</option>';
		}
		echo $str;
		die ();
	}
	public function actionSubdepartment($name) {
		// 找出下属职位信息
		$userInfo = Yii::app ()->user->getUserInfo ();
		$posId = $userInfo ['positionid'];
		$deptId = $userInfo ['deptid'];
		$subPos = Position::subordinatePosition ( $posId );
		$dept = array (
				'' => '全部' 
		);
		if ($subPos) {
			foreach ( $subPos as $k => $v ) {
				$dept [$v ['deptid']] = Dept::getName ( $v ['deptid'] );
			}
		}
		$data = CHtml::dropDownList ( $name, '', $dept );
		$this->ajaxReturn ( $data );
	}
	public function actionSubuser($name) {
		$userInfo = Yii::app ()->user->getUserInfo ();
		$posId = $userInfo ['positionid'];
		// 找出下属员工信息
		$subUser = Position::getSubordinateByPostionId ( $posId );
		$data = CHtml::dropDownList ( $name, '', $subUser );
		$this->ajaxReturn ( $data );
	}
	/**
	 * 将拖动后的数据在数据库中重新排序
	 *
	 * @param array $data
	 *        	拖动后的数组
	 * @return bool
	 */
	protected function resetChildrenOrder($data) {
		$i = 1;
		foreach ( $data as $row ) {
			$result = Position::model ()->updateByPk ( $row ['id'], array (
					'parentid' => $row ['parentid'],
					'order' => $i ++,
					'updatetime' => $_SERVER ['REQUEST_TIME'] 
			) );
			if (! $result)
				return false;
		}
		return true;
	}
	protected function afterAction($action) {
		$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
		$cacheKey = $cacheName [0];
		// Yii::app ()->cache->delete ( $cacheKey );
	}
}
?>